import win32com.client
import os
import time
import pyautogui


class DmOcrSystem:
    def __init__(self):
        self.dm = win32com.client.Dispatch('dm.dmsoft')
        print("大漠版本:", self.dm.Ver())

        # 关键修改1：强制设置绝对路径
        self.script_dir = os.path.dirname(os.path.abspath(__file__))
        self.dm.SetPath(self.script_dir)

        # 关键修改2：显式加载字库文件
        self.font_file = os.path.join(self.script_dir, "game_font.txt")
        if os.path.exists(self.font_file):
            # 3.1232版本必须用SetDict加载字库文件
            ret = self.dm.SetDict(0, self.font_file)
            print(f"字库加载状态: {'成功' if ret == 1 else '失败'}")
        else:
            with open(self.font_file, "w", encoding="gbk") as f:
                f.write("[game_font]\n")
            print("新建空字库文件")




    def recognize_text(self):

        game_window = self.find_game_window("Marvel")
        if game_window:
            game_window.activate()
            time.sleep(1)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

        x1 = game_window_left + 30
        y1 = game_window_top + 50
        x2 = game_window_left + 150
        y2 = game_window_top + 75
        """
        识别指定区域的文字
        :return: 识别结果字符串
        """
        color = "ffffff-202020|aaadaf-202020|dedfdf-202020"
        # 3.1232版本OCR参数：区域坐标 + 颜色 + 相似度
        text = self.dm.Ocr(x1, y1, x2, y2, color, 0.8)
        if text:
            print(f"识别结果: {text}")
            return text
        else:
            print("识别失败！")
            return ""


    def find_game_window(self, partial_title):

        try:
            for i in range(100):
                # 获取所有包含部分标题的窗口
                windows = pyautogui.getWindowsWithTitle(partial_title)

                if windows:
                    print(f"找到 {len(windows)} 个匹配窗口:")
                    for i, win in enumerate(windows, 1):
                        print(f" 完整标题: '{win.title}'")

                    # 返回第一个匹配的窗口
                    return windows[0]
                else:
                    print(f"未找到标题包含 '{partial_title}' 的窗口，重试第'{i + 1}'次...")
                    time.sleep(10)

            print(f"未找到标题包含 '{partial_title}' 的窗口")
            return None
        except Exception as e:
            print(f"查找窗口时出错: {e}")
        return None

if __name__ == '__main__':
    ocr = DmOcrSystem()
    # ocr.test()
    # ocr.add_font_sample("助克拉", "map122.bmp", "FFFFFF")
    # ocr.init_font_lib()
    text = ocr.recognize_text()
    print(f"识别结果: {text}")
    # ocr.save_font_lib()
    # ocr.get_pic()
